#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
配置文件
管理API密钥和其他设置
"""

import os
from typing import Dict, Any

class Config:
    """配置管理类"""
    
    def __init__(self):
        self.config = {
            # 高德地图API配置
            "amap": {
                "api_key": os.getenv("AMAP_API_KEY", ""),
                "base_url": "https://restapi.amap.com/v3",
                "timeout": 10
            },
            
            # 百度地图API配置
            "baidu": {
                "api_key": os.getenv("BAIDU_API_KEY", ""),
                "base_url": "https://api.map.baidu.com",
                "timeout": 10
            },
            
            # 数据库配置
            "database": {
                "path": "huzhou_area_data.db",
                "backup_path": "backup/huzhou_area_data_backup.db"
            },
            
            # 数据采集配置
            "collector": {
                "request_delay": 0.1,  # 请求间隔（秒）
                "max_retries": 3,      # 最大重试次数
                "batch_size": 50       # 批量处理大小
            },
            
            # 输出配置
            "output": {
                "json_file": "huzhou_area_data.json",
                "excel_file": "huzhou_area_data.xlsx",
                "csv_dir": "csv_output"
            },
            
            # 湖州地区配置
            "huzhou_areas": {
                "德清县": {
                    "adcode": "330521",
                    "name": "德清县",
                    "level": "district",
                    "description": "湖州市下辖县"
                },
                "长兴县": {
                    "adcode": "330522",
                    "name": "长兴县",
                    "level": "district", 
                    "description": "湖州市下辖县"
                },
                "安吉县": {
                    "adcode": "330523",
                    "name": "安吉县",
                    "level": "district",
                    "description": "湖州市下辖县"
                }
            }
        }
    
    def get(self, key: str, default: Any = None) -> Any:
        """获取配置值"""
        keys = key.split('.')
        value = self.config
        
        for k in keys:
            if isinstance(value, dict) and k in value:
                value = value[k]
            else:
                return default
        
        return value
    
    def set(self, key: str, value: Any):
        """设置配置值"""
        keys = key.split('.')
        config = self.config
        
        for k in keys[:-1]:
            if k not in config:
                config[k] = {}
            config = config[k]
        
        config[keys[-1]] = value
    
    def get_api_key(self, provider: str) -> str:
        """获取API密钥"""
        return self.get(f"{provider}.api_key", "")
    
    def has_api_key(self, provider: str) -> bool:
        """检查是否有API密钥"""
        return bool(self.get_api_key(provider))
    
    def get_huzhou_areas(self) -> Dict:
        """获取湖州地区配置"""
        return self.get("huzhou_areas", {})
    
    def print_config(self):
        """打印配置信息"""
        print("\n📋 当前配置信息")
        print("="*50)
        
        # API配置
        print("\n🔑 API配置:")
        for provider in ["amap", "baidu"]:
            has_key = self.has_api_key(provider)
            status = "✅ 已配置" if has_key else "❌ 未配置"
            print(f"  {provider.upper()}: {status}")
        
        # 数据库配置
        print(f"\n🗄️ 数据库配置:")
        print(f"  路径: {self.get('database.path')}")
        
        # 输出配置
        print(f"\n📁 输出配置:")
        print(f"  JSON文件: {self.get('output.json_file')}")
        print(f"  Excel文件: {self.get('output.excel_file')}")
        
        # 湖州地区配置
        print(f"\n🏘️ 目标地区:")
        areas = self.get_huzhou_areas()
        for name, info in areas.items():
            print(f"  {name} (代码: {info['adcode']})")


# 全局配置实例
config = Config()

if __name__ == "__main__":
    config.print_config() 